package com.example.lianxi222.register;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.example.lianxi222.R;
import com.example.lianxi222.databinding.ActivityRegisterBinding;
import com.example.mvvm_base.userbean.RegisterEntity;
import com.example.mvvm_base.view.BaseView;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

public class RegisterActivity extends BaseView<ActivityRegisterBinding,RegisterViewModel> {


    @Override
    protected void initData() {
     viewModel.success.observe(this, registerEntity -> {
         if(registerEntity.getCode()==200){
             ToastUtils.showLong(registerEntity.getMessage());
             //环信注册
              new Thread(new Runnable() {
                  @Override
                  public void run() {
                      try {
                          // 注册失败会抛出 HyphenateException。
                          // 同步方法，会阻塞当前线程。
                          EMClient.getInstance().createAccount(registerEntity.getData().getUsername(),registerEntity.getData().getPassword());
                          //成功
                          ToastUtils.showLong("注册成功");
                          //callBack.onSuccess(createLiveData(userName));
                      } catch (HyphenateException e) {
                          //失败
                          ToastUtils.showLong("注册失败"+e.getMessage());
                          //callBack.onError(e.getErrorCode(), e.getMessage());
                      }
                  }
              }).start();


         }else{
             ToastUtils.showLong(registerEntity.getMessage());
         }
     });
     viewModel.failure.observe(this, s -> ToastUtils.showLong("注册失败"+s));
    }

    @Override
    protected void initControlView() {
     viewDataBind.register.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             String username=viewDataBind.registerUsername.getText().toString();
             String password=viewDataBind.registerPassword.getText().toString();
             String repeat=viewDataBind.registerRepeatPassword.getText().toString();
             viewModel.register(username,password,repeat);
         }
     });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public Class<RegisterViewModel> getViewModel() {
        return RegisterViewModel.class;
    }
}